<?php

namespace App\Models\SystemManagement;

use App\Models\CommonModel;
use App\Models\Constant\Fields;
use App\Models\Error;
use App\Models\Api\Files;

class Organization extends CommonModel
{
    protected $table = 'organizations';
    public $primaryKey = 'id';

    protected $hidden = ['deleted_at','created_at','updated_at'];

    /**
     * @param $data 表单提交数据
     * @return string 返回响应结果
     * 添加组织数据
     */
    public static function addData($data){
        //保存数据
        $param = new self();
        $mark = $param->orderBy(Fields::MARK,'desc')->value(Fields::MARK);
        if(is_null($mark)){
            $data['mark'] = 1;
        }else{
            $data['mark'] = seriesNum($mark);
        }

        $re = $param->create($data);
        return $re;
    }

    /**
     * @return mixed
     * 获取组织数据
     */
    public static function getPageData($per){
        $query = self::with('file')->orderBy(Fields::ID)->paginate($per);
        return $query;
    }

    /**
     * @param $id
     * @return mixed
     * 获取单条组织数据
     */
    public static function getOne($id){
        $query = self::with('file')->find($id);
        return $query;
    }

    /**
     * @param $request
     * @return mixed
     * 通过条件查找
     */
    public static function getByCondition($request){
        $query = self::with('file')->where(Fields::Name,'like','%'.$request->name.'%')->get();
        return $query;
    }

    /**
     * @param $arr
     * @return bool
     * 修改某条数据
     */
    public static function updateData($arr,$id){
        $query = self::updateTableData($arr,$id,new self());
        return $query;
    }

    /**
     * @param $ids
     * @return Error
     * @throws \Exception
     * 删除
     */
    static function del($ids){
        $query = self::batchDelTableData($ids,new self());
        return $query;
    }

    /**
     * @param $ids
     * @return Error
     * 恢复
     */
    static function recover($ids){
        $query = self::batchResetTableData($ids,new self());
        return $query;
    }
    /**
     * @return mixed
     * 获取部门数据
     * 转换成数组返回
     */
    public static function getDataToArr(){
        $query = self::orderBy(Fields::ID)
                ->with('file')
                ->get(['id','name','parent_id']);
        return $query;
    }

    function file()
    {
        return $this->belongsTo(Files::class,'logo');
    }
}
